import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false, title: '用户登录' },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { requiresAuth: false, title: '用户注册' },
  },
  {
    path: '/',
    component: () => import('@/layout/Layout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'student',
        name: 'Student',
        meta: { title: '学生端' },
        redirect: '/student/projects',
        children: [
          {
            path: 'projects',
            name: 'StudentProjects',
            component: () => import('@/views/Student.vue'),
            meta: { title: '课题浏览' }
          },
          {
            path: 'matching',
            name: 'ProjectMatching',
            component: () => import('@/views/StudentMatching.vue'),
            meta: { title: '课题匹配' }
          }
        ]
      },
      {
        path: 'mentor',
        name: 'Mentor',
        meta: { title: '导师端' },
        redirect: '/mentor/mentorTopics',
        children: [
          {
            path: 'mentorTopics',
            name: 'MentorTopics',
            component: () => import('@/views/Mentor.vue'),
            meta: { title: '课题浏览' }
          },
          {
            path: 'students',
            name: 'MentorStudents',
            component: () => import('@/views/MentorDuties.vue'),
            meta: { title: '学生管理' }
          },
          {
            path: 'projects',
            name: 'MentorProjects',
            component: () => import('@/views/MentorDuties.vue'),
            meta: { title: '课题指导' }
          }
        ]
      },
      {
        path: 'enterprise',
        name: 'Enterprise',
        meta: { title: '企业端' },
        redirect: '/enterprise/projects',
        children: [
          {
            path: 'projects',
            name: 'EnterpriseProjects',
            component: () => import('@/views/enterprise/TopicList.vue'),
            meta: { title: '我的课题' }
          },
          {
            path: 'projects/create',
            name: 'TopicPublish',
            component: () => import('@/views/enterprise/TopicPublish.vue'),
            meta: { title: '发布课题' }
          },
          {
            path: 'projects/:id/edit',
            name: 'TopicEdit',
            component: () => import('@/views/enterprise/TopicPublish.vue'),
            meta: { title: '编辑课题' },
            props: true
          },
          {
            path: 'applications',
            name: 'EnterpriseApplicationList',
            component: () => import('@/views/enterprise/ApplicationList.vue'),
            meta: { title: '申请管理' }
          },
        ]
      },
      {
        path: 'admin',
        name: 'Admin',
        meta: { title: '管理端' },
        redirect: '/admin/dashboard',
        children: [
          {
            path: 'dashboard',
            name: 'dashboard',
            component: () => import('@/views/admin/DashBoard.vue'),
            meta: { title: '汇总' }
          },
          {
            path: 'user',
            redirect: '/admin/user/list',
            meta: {
              title: '用户管理',
              icon: 'User'
            },
            children: [
              {
                path: 'list',
                name: 'UserList',
                component: () => import('@/views/admin/UserManagement.vue'),
                meta: { title: '用户列表' }
              }
            ]
          },
          {
            path: 'project',
            redirect: '/admin/project/list',
            meta: {
              title: '课题管理',
              icon: 'Document'
            },
            children: [
              {
                path: 'list',
                name: 'ProjectList',
                component: () => import('@/views/admin/ProjectManagement.vue'),
                meta: { title: '课题列表' }
              }
            ]
          },
          {
            path: 'application',
            redirect: '/admin/application/list',
            meta: {
              title: '申请管理',
              icon: 'Reading'
            },
            children: [
              {
                path: 'list',
                name: 'ApplicationList',
                component: () => import('@/views/admin/ApplicationManagement.vue'),
                meta: { title: '申请列表' }
              }
            ]
          }
        ]
      },
      {
        path: 'chat',
        name: 'Chat',
        component: () => import('@/views/Chat.vue'),
        meta: { title: '聊天' }
      },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { requiresAuth: false, title: '页面不存在' },
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useAuthStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 中山大学研究生院校企对接平台`
  }

  // 如果有token但没有用户信息，尝试初始化
  if (userStore.token && !userStore.userInfo) {
    await userStore.initializeUserInfo()
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth === false) {
    // 登录和注册页面，如果已登录则跳转到首页
    if (userStore.token && (to.path === '/login' || to.path === '/register')) {
      next('/')
      return
    }
    next()
    return
  }

  // 需要认证的页面
  if (!userStore.token) {
    // 未登录，跳转到登录页
    next('/login')
    return
  }

  // 已登录访问根路径时，按角色重定向到各自首页
  if (to.path === '/') {
    const role = userStore.userInfo?.role
    if (role) {
      let target = '/student/projects'
      if (role === 'student') {
        target = '/student/projects'
      } else if (role === 'mentor' || role === 'tutor') {
        target = '/mentor/mentorTopics'
      } else if (role === 'enterprise') {
        target = '/enterprise/projects'
      } else if (role === 'admin') {
        target = '/admin/dashboard'
      }
      if (to.path !== target) {
        next(target)
        return
      }
    }
  }

  // 检查角色权限
  // if (to.meta.role && userStore.token !== to.meta.role) {
  //   next('/') // 没有权限则跳转到首页
  //   return
  // }


  next()
})

export default router
